import { h, defineComponent, ref, watchEffect, inject, KeepAlive, Transition, Suspense } from 'vue'
import { handleActivePath } from '@/router/utils'
import { storeToRefs } from 'pinia'
import { useTabsStore } from '@/stores/modules/tabs'
import { themesStore } from '@/stores/modules/theme'
import { useRoute, RouterView } from 'vue-router'
import type { VNode } from 'vue'
import type { lockState } from '@/types/tabs'
import { NSpin } from 'naive-ui'
import routerStyle from './styles/index.module.scss'
export default defineComponent({
  name: 'YangRouter',
  setup() {
    const $clone = inject('$clone') as <T>(data: T) => T
    const route: any = useRoute()
    const tabsStore = useTabsStore()
    const themeStore = themesStore()
    const { getVisitedRoutes: visitedRoutes, getLocaks: locks } = storeToRefs(tabsStore)
    const { getAnimation: animation } = storeToRefs(themeStore)
    const routerKey = ref()
    const keepList = ref([])
    watchEffect(() => {
      routerKey.value = handleActivePath(route, true)
      const arr = $clone(locks.value).map((el: lockState) => {
        return el.childer
      })
      arr.push($clone(visitedRoutes.value))
      keepList.value = arr.flat().map((el: any) => {
        return el.name
      })
    })
    const routerSlots = {
      default: ({ Component }: { Component: VNode }) =>
        Component && (
          <Transition name={animation.value} mode="out-in">
            <KeepAlive include={keepList.value}>
              <div class={routerStyle.routerName}>{h(Component, { key: routerKey.value })}</div>
            </KeepAlive>
          </Transition>
        )
    }
    const slots = {
      default: () => <RouterView v-slots={routerSlots} />,
      fallback: () => (
        <div class="flex justify-center pt-[30px]">
          <NSpin size={'large'} />
        </div>
      )
    }
    return () => (
      <>
        <Suspense v-slots={slots}></Suspense>
      </>
    )
  }
})
